<script lang="js">
import {defineComponent} from 'vue'
import {fetchEventSource} from "@fortaine/fetch-event-source";
// import {stream} from '../utils/chat'

export default defineComponent({
  name: "SseDemo2",
  data() {
    return {
      typedMessage: ''
    }
  },
  methods: {
    onFinish(resText) {
      this.typedMessage = resText
    },
    startListening() {
      let responseText = "";
      let remainText = "";
      let finished = false;
      let running = false;

      const finish = () => {
        finished = true;
        this.onFinish(responseText+remainText)
      }
      fetchEventSource("http://localhost:8080", {
        onmessage: (event) => {
          if (event.data === "[DONE]" || finished) {
            return finish();
          }
          console.log('update', event.data)
          // this.typedMessage += event.data
          // 这样不会有打字稿效果
          const chunk = event.data
          if (chunk) {
            remainText += chunk;
          }
        },
        onclose() {
          finish();
        },
      })
    }
  },
  mounted() {
    this.startListening();
  }
})
</script>

<template>
  <div>
    <div>SseDemo3</div>
    <div>{{ typedMessage }}</div>
  </div>
</template>

<style scoped>

</style>
